package com.vnp.cooking.fragmentKitchen;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vnp.cooking.DangCongThucActivity;
import com.vnp.cooking.R;
import com.vnp.cooking.UIcontrols.MyCircleImageView;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.Common;
import com.vnp.cooking.utils.DecodeUtils;
import com.vnp.cooking.utils.PreferenceHelper;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.CursorJoiner.Result;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;

public class CoverCanhan1 extends Fragment implements OnClickListener {

	View v;
	private static final String KEY_CONTENT = "FrgGianbepcuatoi:Content";
	private String mContent = "???";
	private static final String TEMP_COVER_FILE = "avatar.jpeg";
	private static final int CHANGE_AVATAR = -1;
	
	// image avatar
	MyCircleImageView imgAvatar;
	TextView txtNameLevel, txtCity;
	DisplayImageOptions options = new DisplayImageOptions.Builder()
									.cacheInMemory(false)
									.cacheOnDisc(false)
									.bitmapConfig(Config.RGB_565)
									.build();
	
	PreferenceHelper preferenceHelper;
	public static CoverCanhan1 newInstance(String content) {
		CoverCanhan1 fragment = new CoverCanhan1();
		fragment.mContent = content;
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if ((savedInstanceState != null)
				&& savedInstanceState.containsKey(KEY_CONTENT)) {
			mContent = savedInstanceState.getString(KEY_CONTENT);
		}
		preferenceHelper = new PreferenceHelper(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v = (View) inflater.inflate(R.layout.cover_canhan_1, container,
				false);
		
		imgAvatar = (MyCircleImageView) v.findViewById(R.id.img_avatar);
		txtNameLevel = (TextView) v.findViewById(R.id.level_user);
		txtCity = (TextView) v.findViewById(R.id.city_user);
		ImageLoader.getInstance().displayImage(preferenceHelper.getUserUrlAvatar(), imgAvatar, options);
		init();
		return v;
	}
	
	
	void init() {
		imgAvatar.setOnClickListener(this);
		txtNameLevel.setText(preferenceHelper.getUserLevelName());
		Log.i("DATA", preferenceHelper.getUserLevelName());
		txtCity.setText(preferenceHelper.getNameCity());
	}
	

	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(KEY_CONTENT, mContent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_avatar:
			
			Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			i.setType("image/*");
			getParentFragment().startActivityForResult(i, CHANGE_AVATAR);
			
			break;

		default:
			break;
		}
	}
	
	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("DATA", "Nhay vao result ben ngoai--------------");
		 Fragment fragment = (Fragment) getChildFragmentManager().findFragmentByTag("KEY_CONTENT");
	      if(fragment != null){
	            fragment.onActivityResult(requestCode, resultCode, data);
	      }
		if (data != null && resultCode == Activity.RESULT_OK && requestCode == CHANGE_AVATAR) {
			Log.i("DATA", "Nhay vao result ben trong--------------");
				onChangeAvatar(requestCode, resultCode, data);
		} else {
			Toast.makeText(getActivity(), "Bạn chưa chọn ảnh", Toast.LENGTH_SHORT).show();
		}
		
	}

	// change avatar
	void onChangeAvatar(int requestCode, int resultCode, Intent data) {
		Log.i("DATA", "Nhay vao day--------------");
		Uri u = (Uri) data.getData();
		String[] filePathColumn = { MediaStore.Images.Media.DATA };
		Cursor cursor = getActivity().getContentResolver().query(u, filePathColumn, null, null, null);
		cursor.moveToFirst();
		int columnIndex        = cursor.getColumnIndex(filePathColumn[0]);
		final String file_path = cursor.getString(columnIndex);
		
		 // bimatp factory
		Bitmap bm = DecodeUtils.decode(getActivity(), Uri.parse(file_path), 800, 800);
		imgAvatar.setScaleType(ScaleType.CENTER_CROP);
		imgAvatar.setImageBitmap(bm);
		
		// xu li phan upload tai day
		RequestParams params = new RequestParams();
		params.put("user_id", preferenceHelper.getID());
		try {
			params.put("fileUpload", new File(file_path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		AsyncHttpClient client = new AsyncHttpClient();
		client.post("http://anuong.net/api/user/avatar", params, new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				// TODO Auto-generated method stub
				super.onFailure(error);
			}
			

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					switch (status) {
					case 200:
						JSONObject data = re.getJSONObject("data");
						String avatar = data.getString("url");
						Log.i("DATA", "Avatar: "+avatar);
						preferenceHelper.setUserURLAvatar(avatar);
						Log.i("DATA", "THanh cong");
						break;
					case 400:
						Log.i("DATA", "Thieu truong");
						break;
					case 404:
						Log.i("DATA", "ID khong chuan");
						break;

					default:
						break;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			
		});
		
		
		cursor.close();
	}
	

}
